//
//  LWAccountViewController.m
//  LWShopItem
//
//  Created by mac on 17/5/4.
//  Copyright © 2017年 LWShop.com. All rights reserved.
//

#import "LWAccountViewController.h"
#import "LWAccountAddressCell.h"
#import "LWAccountGoodCell.h"
#import "LWAccountSelectCell.h"
#import "LWAccountPayView.h"
#import "CZAdditions.h"
#import "LWAccountOfferView.h"
#import <Masonry.h>
#import "LWLWAccountSelectDetailHeader.h"
#import "LWAccountGoodHeader.h"
#import "LWAddLocationVc.h"
#import "LWAccountModel.h"
#import "LWAddressViewController.h"
#import "LWGroupList.h"
#import "NSMutableArray+LW.h"
#import "DWWXSDK.h"


static NSString *addressCell = @"addressCell";
static NSString *goodCell = @"goodCell";
static NSString *selectCell = @"selectCell";
static NSString *goodHeader = @"goodHeader";
static NSString *selectDetailHeader = @"selectDetailHeader";

@interface LWAccountViewController ()<LWAddLocationVcDelegate,LWDetilVcDelegate>

@property(nonatomic,strong)LWAccountOfferView *offerView;



@end

@implementation LWAccountViewController
{
    NSArray<NSDictionary *> *_accountOfferDetailArr;
    
    // 泛型
    NSMutableArray<LWAccountModel *>* _contactList;
    
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    UIBarButtonItem *backBtnItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"返回"] style:UIBarButtonItemStylePlain target:self action:@selector(backCLick)];
    
    self.navigationItem.leftBarButtonItem = backBtnItem;
    
    _accountOfferDetailArr = @[@{@"优惠券":@"可用优惠券"},@{@"配送方式":@"顺丰物流"},@{@"发票":@"不需要"},@{@"支付方式":@"微信支付"}];
    double sum = [self calcilateTotalOffer];
    
    self.view.backgroundColor = [UIColor cz_colorWithRed:255 green:200 blue:200];
    [self.navigationController.navigationBar setTintColor:[UIColor blackColor]];
    self.title = @"收银台";
    
    LWAccountPayView *payView = [LWAccountPayView accountPayView];
    payView.frame = CGRectMake(0, 0, 0, 260);
    self.tableView.tableFooterView = payView;
    payView.sum = sum;
    
    
   
    LWAccountOfferView *offerView = [LWAccountOfferView offerView];
    __weak __typeof(self)weakSelf = self;
    
    offerView.frame = CGRectMake(0, self.view.bounds.size.height - 30, self.view.bounds.size.width, 50);
    [[UIApplication sharedApplication].keyWindow addSubview:offerView];
    _offerView = offerView;
    offerView.sum = sum;
    
//    //微信支付
//    [offerView.payNow addTarget:self action:@selector(wechatPay) forControlEvents:UIControlEventTouchUpInside];
    
    //遍历商品
    [offerView.payNow addBlockForControlEvents:UIControlEventTouchUpInside block:^(id  _Nonnull sender) {
        
        [weakSelf.accountArr enumerateObjectsUsingBlock:^(LWDetailModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
         //在这里获取需要支付的货物信息
                    NSLog(@"---->打印ID%@", obj.goods_id);
                    NSLog(@"----->打印对应数量num%ld",(long)obj.orderCount);
        
                    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        
                    dic[@"goods_id"] = obj.goods_id;
        
                    NSLog(@"%ld", (long)obj.orderCount);
        
                    dic[@"goods_num"] = [NSString stringWithFormat:@"%ld",(long)obj.orderCount];
                    dic[@"token"] = [[NSUserDefaults standardUserDefaults] objectForKey:@"token"];
                    dic[@"user_id"] = [[NSUserDefaults standardUserDefaults] objectForKey:@"user_id"];
        
                    [HYBNetworking postWithUrl:@"index.php?m=Api&c=Cart&a=addCart" refreshCache:YES params:[LWUtilityClass isDict:dic] success:^(id response) {
        
                        NSLog(@"发送列表成功");
        
                    } fail:^(NSError *error) {
        
                        NSLog(@"%@",error);
        
        }];
            
            NSMutableDictionary *dict = [NSMutableDictionary dictionary];
            
            dict[@"token"] = [[NSUserDefaults standardUserDefaults] objectForKey:@"token"];
            dict[@"user_id"] = [[NSUserDefaults standardUserDefaults]objectForKey:@"user_id"];
            dict[@"act"] = @"submit_order";
            dict[@"address_id"] = [[NSUserDefaults standardUserDefaults]objectForKey:@"result"];
            dict[@"shipping_code"] = @"shunfeng";
            
            [HYBNetworking postWithUrl:@"index.php?m=Api&c=Cart&a=cart3" refreshCache:YES params:[LWUtilityClass isDict:dict] success:^(id response) {
                
                NSLog(@"---------%@----------",dict);
                
               
                
                
            } fail:^(NSError *error) {
                
                
                NSLog(@"%@",error);
                
                
            }];
            
        }];
        
        [self wechatPay];
        
    }];
    
    [self.tableView registerClass:[LWAccountAddressCell class] forCellReuseIdentifier:addressCell];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"LWAccountGoodCell" bundle:nil] forCellReuseIdentifier:goodCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"LWAccountSelectCell" bundle:nil] forCellReuseIdentifier:selectCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"LWAccountGoodHeader" bundle:nil] forHeaderFooterViewReuseIdentifier:goodHeader];
    [self.tableView registerNib:[UINib nibWithNibName:@"LWAccountSelectDetailHeader" bundle:nil] forHeaderFooterViewReuseIdentifier:selectDetailHeader];
}
- (void)wechatPay
{
    double sum = [self calcilateTotalOffer];
    //Trade_type:@"APP"
    //Out_trade_no:商户系统内部的订单号,32个字符内、可包含字母
    DWWXSDK *wxsdk = [DWWXSDK wxSDK];
    NSString *xmlString = [wxsdk dw_obtainWXPayXmlAppid:@"wxd21cf7d764a8a393" mch_id:@"1481812502" partnerKey:@"wxsdlinwangd21cf7d764a8a393afgj6" body:@"临网商品" out_trade_no:[self generateTradeNumber] total_fee:sum * 100 notify_url:@"www.baidu.com"];
    [wxsdk dw_wxRequestType:DWWXPayMoney xmlString:xmlString success:^(BOOL success) {
        NSLog(@"支付成功");
    } result:^(DWWXOperatingResult operatingResult, NSString *error, NSString *errorMsg) {
        NSLog(@"错误码:%ld\n%@\n错误Log:%@", operatingResult, error, errorMsg);
    }];

}
#pragma MARK - 随机订单号
-(NSString *)generateTradeNumber
{
    static int kNumber = 12;
    NSString *sourceStr = @"0123456789";
    NSMutableString *resultStr = [[NSMutableString alloc] init];
    srand((unsigned)time(0));
    for (int i = 0; i < kNumber; i++) {
        unsigned index = rand() % [sourceStr length];
        NSString *oneStr = [sourceStr substringWithRange:NSMakeRange(index, 1)];
        [resultStr appendString:oneStr];
    }
    //  NSLog(@"随机字符串:%@",resultStr);
    return resultStr;
}

#pragma MARK - 数据存储的方法
- (void)saveData
{
    //获取路径
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES).lastObject  stringByAppendingString:@"LWperson.db"];
    
    
    //归档
    [NSKeyedArchiver archiveRootObject:_contactList toFile:filePath];
    
    
}
#pragma MARK - Data
- (void)loadData
{
    //从文件读取
    //获取路径
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES).lastObject  stringByAppendingString:@"LWperson.db"];
    
    //读取数据
    _contactList = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
    
    //如果没有值 实例化_contactList
    if (_contactList == nil) {
        
        _contactList = [NSMutableArray array];
        
    }
    
}

#pragma mark - backCLick
- (void)backCLick
{
    [self.navigationController popViewControllerAnimated:YES];
    
    [_offerView removeFromSuperview];
    
}
#pragma mark - UITableViewDataSource UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (_accountArr.count) {
        return 3;
    } else {
        return 2;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    } else if (section == 1) {
        if (_accountArr.count) {
            return _accountArr.count;
        } else {
            return 4;
        }
    } else {
        return 4;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell;
    if (indexPath.section == 0) {
        
        cell = [tableView dequeueReusableCellWithIdentifier:addressCell forIndexPath:indexPath];
        
        
        ((LWAccountAddressCell *)cell).model = [_contactList objectAtIndexCheck:indexPath.row];
        
    } else if (indexPath.section == 1) {
        if (_accountArr.count) {
            cell = [tableView dequeueReusableCellWithIdentifier:goodCell forIndexPath:indexPath];
            ((LWAccountGoodCell *)cell).model = _accountArr[indexPath.row];
        } else {
            cell = [tableView dequeueReusableCellWithIdentifier:selectCell forIndexPath:indexPath];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            ((LWAccountSelectCell *)cell).dict = _accountOfferDetailArr[indexPath.row];
        }
    } else {
        cell = [tableView dequeueReusableCellWithIdentifier:selectCell forIndexPath:indexPath];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        ((LWAccountSelectCell *)cell).dict = _accountOfferDetailArr[indexPath.row];
    }
    cell.contentView.backgroundColor = [UIColor whiteColor];
    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 80;
    } else if (indexPath.section == 1) {
        if (_accountArr.count) {
            return 110;
        } else {
            return 60;
        }
    } else {
        return 60;
    }
}
#pragma mark - UITableViewDelegate
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *header;
    if (section == 0) {
        return nil;
    } else if (section == 1) {
        if (_accountArr.count) {
            header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:goodHeader];
        } else {
            header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:selectDetailHeader];
        }
    } else {
        header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:selectDetailHeader];
    }
    return header;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 0;
    } else if (section == 1) {
        if (_accountArr.count) {
            return 15;
        } else {
            return 40;
        }
    }else {
        return 40;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        
        NSLog(@"点击了添加地址");
        
        
        _offerView.hidden = YES;
        
        LWAddLocationVc *vc = [LWAddLocationVc new];
        
        
        vc.delegate = self;
        
        [self.navigationController pushViewController:vc animated:YES];
        
        
        
        
    }
}

//解决从添加地址控制器返回来的时候  底部的视图消失的bug
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    _offerView.hidden = false;
    
    [self loadData];
    [self.tableView reloadData];
}
- (void)dealloc {
    [_offerView removeFromSuperview];
}

#pragma mark - 计算总共应付的钱数
- (double)calcilateTotalOffer {
    __block double sum = 0;
    [_accountArr enumerateObjectsUsingBlock:^(LWDetailModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        sum += obj.orderCount * obj.shop_price.doubleValue;
    }];
    return sum;
}

- (NSArray<LWDetailModel *> *)accountArr {
    if (!_accountArr) {
        _accountArr = [NSArray array];
    }
    return _accountArr;
}

@end
